package yxy.game.pm2.module;

import java.util.Collection;

import yxy.game.pm2.Result;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.module.rank.IWorshipableRank;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.message.PackageMessage;

public class RankWorshipHandle {
	public Result worship(String playerCode, int ranking, IWorshipableRank rank, Currencies rewards, RankWorshipEntry worshipEntry) {
		if (ranking > rank.topSize()) {
			return Result.WorshipLow;// 排名太低不能膜拜
		}
		RankWorshipPlayer rankWorshipPlayer = RankWorshipPlayer.get(playerCode, rank.getWorship());
		if (rankWorshipPlayer.remainTimes() <= 0) {
			return Result.WorshipTimesOut;// 没有膜拜次数了
		}

		RankEntry entry = rank.entryByRanking(ranking);
		if (entry == null) {
			return Result.ParamError;// 膜拜的名次没有人
		}
		String code = entry.getKey();
		if (code.equals(playerCode)) {
			return Result.WorshipSelf;// 不要脸，不能膜拜自己
		}
		if (rankWorshipPlayer.getWorshiped().contains(code)) {
			return Result.WorshipDone;// 已经膜拜过了
		}
		try {
			if (rankWorshipPlayer.tryLock()) {
				long fans = rank.getWorship().worship(code);
				rankWorshipPlayer.getWorshiped().add(code);
				rankWorshipPlayer.set();

				worshipEntry.setFans(fans);
				worshipEntry.setTimes(rankWorshipPlayer.remainTimes());

				if (rewards != null) {
					new CurrencyHandle().addCurrency(playerCode, CCReason.排行榜膜拜, rewards);
					worshipEntry.setRewards(new CurrencyHandle().packItems(rewards));
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			return Result.DataError;
		} finally {
			rankWorshipPlayer.unlock();
		}
		return Result.Success;
	}

	static public class RankWorshipEntry {
		private long fans;
		private Collection<PackageMessage.Item> rewards;
		private int times;

		public long getFans() {
			return fans;
		}

		private void setFans(long fans) {
			this.fans = fans;
		}

		public Collection<PackageMessage.Item> getRewards() {
			return rewards;
		}

		private void setRewards(Collection<PackageMessage.Item> rewards) {
			this.rewards = rewards;
		}

		public int getTimes() {
			return times;
		}

		private void setTimes(int times) {
			this.times = times;
		}

	}
}
